# -*- coding: utf-8 -*-
from __future__ import unicode_literals

import re
from collections import OrderedDict
import hashlib

from .pair_base import PairBase

class SingleCharPair(PairBase):
    """
    SingleCharPair parser
    单字符对解析
    """
    def __init__(self, content, key_char, cache_key, paragraph_index):
        super(SingleCharPair, self).__init__(content, key_char, cache_key)
        self.paragraph_index = paragraph_index

    @property
    def states(self):
        return {
            'normal': 0, # init, cache -->
            'ignore': 1, # \ cache -->
            'cache': 2 # normal -->, ignore
        }

    def parse(self):
        '''执行解析操作'''
        # init state is normal
        state = self.states['normal']
        i = 0
        start = None
        end = None
        store = OrderedDict()
        while i < len(self.content):
            _c = self.content[i]
            # print(_c, self._getStateKey(state))
            if _c == self.key_char:
                if state == self.states['normal']:
                    state = self.states['cache']
                    start = i
                elif state == self.states['ignore']:
                    state = self.states['cache']
                elif state == self.states['cache']:
                    state = self.states['normal']
                    end = i + 1
                    if not start is None and not end is None:
                        if end - start > 2:
                            _k = '@{0}_[{1}_{2}_{3}]'.format(
                                self.cache_key,
                                str(self.paragraph_index),
                                str(start),
                                str(end)
                            )
                            try:
                                _k_md5 = hashlib.md5(_k).hexdigest()
                            except Exception as ex:
                                _k_md5 = hashlib.md5(_k.encode('utf-8', 'ignore')).hexdigest()
                            _k = '{0}{{{1}}}'.format(
                                '$',
                                _k_md5
                            )
                            store[_k] = {
                                'content': self.content[start : end],
                                'start': start,
                                'end': end
                            }
                    start = None
                    end = None
            else:
                if state == self.states['cache'] or state == self.states['ignore']:
                    if _c == self.escape_char:
                        state = self.states['ignore']
            i += 1

        return self._wrapperResult(store)